package com.ruoyi.exam.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.exam.dto.ExamGenerateRequest;
import com.ruoyi.exam.dto.ExamAnswerRequest;
import com.ruoyi.exam.service.ExamApiService;
import com.ruoyi.common.annotation.Anonymous;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;

@RestController
@Anonymous
@RequestMapping("/exam")
public class ExamApiController {

    @Autowired
    private ExamApiService examApiService;

    /**
     * 生成试卷（教师用）
     */
    @PostMapping(value = "/generate", produces = MediaType.TEXT_EVENT_STREAM_VALUE)

//    @PreAuthorize("@ss.hasPermi('exam:generate')")
    public SseEmitter generateExamPaper(@RequestBody ExamGenerateRequest request) {
        return examApiService.generateExamPaper(
            request.getSubject(),
            request.getTeacherId(),
            request.getClassId(),
            request.getStartTime(),
            request.getEndTime()
        );
    }

//    /**
//     * 获取学生可参加的考试列表
//     */
//    @GetMapping("/student/exams")
//    public AjaxResult getStudentExams(@RequestParam Long studentId) {
//        try {
//            String result = examApiService.getStudentExams(studentId);
//            return AjaxResult.success(result);
//        } catch (IOException e) {
//            e.printStackTrace();
//            return AjaxResult.error("获取考试列表失败: " + e.getMessage());
//        }
//    }

    /**
     * 提交学生答案
     */
    @PostMapping("/answer/submit")
    public AjaxResult submitStudentAnswer(@RequestBody ExamAnswerRequest request) {
        try {
            String result = examApiService.submitStudentAnswer(
                request.getPaperId(),
                request.getStudentId(),
                request.getQuestionId(),
                request.getAnswer()
            );
            return AjaxResult.success("提交成功", result);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("提交答案失败: " + e.getMessage());
        }
    }
}
